package day_2022_9_to_12.Day;

/**
 * @author haomin
 * @date 2022/09/23 16:24
 **/
public class Day21_1_Num707_MyLinkedList {
    class ListNode {
        int val;
        ListNode next;

        ListNode (int val){
            this.val = val;
        }
    }
    class MyLinkedList {
        int size;
        ListNode head;

        public MyLinkedList() {
            size = 0;
            head = new ListNode(-1);
        }

        public int get(int index) {
            if(index < 0 || index >= size) return -1;
            ListNode cur = head;
            for(int i = 0; i <= index; ++i){
                cur = cur.next;
            }
            return cur.val;
        }

        public void addAtHead(int val) {
            ListNode cur = new ListNode(val);
            cur.next = head.next;
            head.next = cur;
            size++;
        }

        public void addAtTail(int val) {
            ListNode cur = head;
            while(cur.next != null) cur = cur.next;
            cur.next = new ListNode(val);
            size++;
        }

        public void addAtIndex(int index, int val) {
            if(index <= 0) addAtHead(val);
            else if(index == size) addAtTail(val);
            else if(index >= size) {}
            else{
                ListNode cur = head;
                for(int i = 0; i < index; ++i){
                    cur = cur.next;
                }
                ListNode newNode = new ListNode(val);
                newNode.next = cur.next;
                cur.next = newNode;
                size++;
            }
        }

        public void deleteAtIndex(int index) {
            if(index < 0 || index >= size) return;
            ListNode cur = head;
            for(int i = 0; i < index; ++i){
                cur = cur.next;
            }
            ListNode next = cur.next;
            cur.next = cur.next.next;
            next.next = null;
            size--;
        }
    }
}